#!/usr/local/python36/bin/python3.6
# coding: utf-8
#jipeng 2016.8.11
#python2将zabbix报警信息发送到微信。
#脚本中*****需要修改的地方


import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import requests
import  json
def senddata(send_to_users,recevier_server_smtp,recevier_user,recevier_pwd,content,Subject,action_id):
    # sender = send_to_users
    # recevier_user = recevier_user
    # smtpserver = recevier_server_smtp #发送邮箱服务器
    # username = recevier_user
    # password = recevier_pwd
    # content="xxxxt"
    # msg = MIMEText(content, 'text', 'utf-8')
    # msg["From"] = formataddr(["x1",recevier_user])
    # msg["To"] = formataddr(["x2",sender])
    # msg['Subject'] = "xxx"
    #
    # smtp = smtplib.SMTP_SSL(smtpserver,port=465)
    # # smtp.connect(smtpserver)
    # smtp.login(username, password)
    # print("_______________________________")
    # print(msg)
    # smtp.sendmail(recevier_user,sender, "xdsfa")
    # smtp.quit()
    msg = MIMEText(content, 'plain', 'utf-8')
    # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['From'] = formataddr([recevier_user, recevier_user])
    # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['To'] = formataddr([send_to_users, send_to_users])
    # 邮件的主题


    msg['Subject'] = Subject + action_id

    # SMTP服务器，腾讯企业邮箱端口是465，腾讯邮箱支持SSL(不强制)， 不支持TLS
    # qq邮箱smtp服务器地址:smtp.qq.com,端口号：456
    # 163邮箱smtp服务器地址：smtp.163.com，端口号：25
    server = smtplib.SMTP_SSL(recevier_server_smtp, 465)
    # 登录服务器，括号中对应的是发件人邮箱账号、邮箱密码
    server.login(recevier_user, recevier_pwd)
    # 发送邮件，括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.sendmail(recevier_user, [send_to_users,], msg.as_string())
    # 关闭连接
    server.quit()
    # print("-------------------------邮件发送成功%s------------------------" %(send_to_users))
    # print(msg)
    # 如果 try 中的语句没有执行，则会执行下面的 ret=False

def senddata_slack(webhook,content,Subject,action_id,slack_webhook_index):

    url = webhook[slack_webhook_index]
    data = {
        "text":content
    }
    headers = {'content-type': 'application/json'}
    requests.post(url, data=json.dumps(data), headers=headers)

def senddata_weixin(webhook,content,Subject,action_id,weixin_webhook_index):

    url = webhook[weixin_webhook_index]

    data = {
        "msgtype": "text",
        "text": {
            "content": content
        }
    }
    headers = {'content-type': 'application/json'}
    ret = requests.post(url, data=json.dumps(data), headers=headers)
    print("------------------weixin print---------------------")
    print(ret.status_code)
    print(ret.content)
